import { NextRequest, NextResponse } from "next/server";
import prisma from "../../../../../lib/prisma";

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ chatId: string }> }
) {
  try {
    const { chatId } = await params;
    const { newMessage } = await request.json();

    // 查找现有聊天
    const chat = await prisma.chat.findUnique({
      where: { id: chatId },
    });

    if (!chat) {
      return NextResponse.json({ error: "Chat not found" }, { status: 404 });
    }

    // 直接用新消息覆盖原有 messages 数组
    const updatedChat = await prisma.chat.update({
      where: { id: chatId },
      data: { messages: [newMessage] },
    });

    return NextResponse.json({ chat: updatedChat });
  } catch (error) {
    console.error(error); // 打印错误以便调试
    return NextResponse.json({ error: "Server error" }, { status: 500 });
  }
}

// export async function PUT(request: NextRequest) {
//   try {
//     const { userId, chatTitle, initialMessage } = await request.json();

//     // 创建新聊天
//     const newChat = await prisma.chat.create({
//       data: {
//         userId,
//         chatTitle,
//         messages: [initialMessage],
//       },
//     });

//     return NextResponse.json({ chat: newChat });
//   } catch (error) {
//     return NextResponse.json({ error: "Server error" }, { status: 500 });
//   }
// }
